from redis import Redis, ConnectionPool


class Mredis():
    def __init__(self):
        self.pool = ConnectionPool(host='localhost', port=6379, db=0, password='Msy2014159')
        self.r = Redis(connection_pool=self.pool)
        # self.r = Redis(host='124.71.227.70',port=6379)

    def pipeline(self):
        """
        返回一个Redis pipeline对象，用于执行批量操作。
        """
        return self.r.pipeline()

    # 字符串 添加  获取  删除  自增  自减
    def set_str(self, key, value):
        return self.r.set(key, value)

    # times单位为秒
    def setex_str(self, key, times, value):
        return self.r.setex(key, times, value)

    def setnx_str(self, key, value):
        return self.r.setnx(key, value)

    def str_incr(self, key, value):
        return self.r.incr(key, value)

    def get_str(self, key):
        value = self.r.get(key)
        if value:
            value = value.decode()
        return value

    # 加
    def incr_str(self, key, count):
        return self.r.incr(key, count)

    def decr_str(self, key, count):
        return self.r.decr(key, count)

    def str_del(self, *key):
        return self.r.delete(*key)

    # hash,添加
    def hash_add(self, key, field, value):
        return self.r.hset(key, field, value)

    # 获取对象的所有属性
    def hash_getall(self, key):
        return self.r.hgetall(key)

    # 获取对象的某个属性的值
    def hash_getone(self, key, field):
        return self.r.hget(key, field)

    # 删除对象的某个属性
    def hash_hdel(self, key, field):
        return self.r.hdel(key, field)

    # 模糊查询
    def get_key(self, key):
        return self.r.keys(key)

    # list
    def list_push(self, key, value):
        return self.r.rpush(key, value)

    def list_pop(self, key):
        return self.r.lpop(key)

    def list_lrange(self, key, min, max):
        return self.r.lrange(key, min, max)

    def list_len(self, key):
        return self.r.llen(key)

    def list_del(self, key, field):
        return self.r.lrem(key, 1, field)

    def list_rpoplpush(self, list1, list2):
        return self.r.rpoplpush(list1, list2)

    # zset
    def zset_zadd(self, key, score, value):
        map = {value: score}
        return self.r.zadd(key, mapping=map)

    def zset_zrem(self, key, value):
        return self.r.zrem(key, value)

    def zset_zrangebyscore(self, key, min, max):
        return self.r.zrangebyscore(key, min, max)

    # 原子性操作的方法


# import time
r = Mredis()